﻿#region License
/*
 * Copyright ©2011-2012 EasyMon Project
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *  
 */
#endregion

using System;
using System.Runtime.Serialization;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace EasyMon.Common.Sources
{
    [DataContract, Serializable,
    XmlRoot(ElementName = "sourceRoot", IsNullable = true, Namespace = "http://easy-mon.googlecode.com/files/easy-mon-configuration-v1.xsd")]
    public class SourceRoot
    {
        [DataMember, XmlAttribute("description")]
        public string Description { get; set; }

        [DataMember, XmlElement("product")]
        public ProductSource[] Products { get; set; }

        public static XmlReaderSettings XmlReaderSettings { get; private set; }

        public static XmlWriterSettings XmlWriterSettings { get; private set; }

        static SourceRoot()
        {
            XmlReaderSettings = new XmlReaderSettings();

            XmlWriterSettings = new XmlWriterSettings
            {
                Encoding = Encoding.UTF8,
                Indent = true,
                IndentChars = "\t"
            };
        }
        public static SourceRoot Load(string url)
        {
            using (var reader = XmlReader.Create(url, XmlReaderSettings))
            {
                return Load(reader);
            }
        }
        public static SourceRoot Load(XmlReader reader)
        {
            return new XmlSerializer(typeof(SourceRoot)).Deserialize(reader) as SourceRoot;
        }

        public void Save(string fileName)
        {
            using (var writer = XmlWriter.Create(fileName, XmlWriterSettings))
            {
                Save(writer);
            }
        }

        public void Save(XmlWriter writer)
        {
            new XmlSerializer(typeof(SourceRoot)).Serialize(writer, this);
        }
    }
}
